package com.ukao.pad.usbrfidreader;

import android.annotation.SuppressLint;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Handler;
import android.util.Log;


import com.ukao.pad.R;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.printer.CheckPrinterHelper;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.T;
import com.ukao.pad.utils.Utils;

import static com.ukao.pad.eventbus.MembershipCardEvent.Message.fali;


/**  Usb 读卡帮助类
 * Created by ukaodev on 2018/3/1.
 */
public class UsbrfidReaderHelper {
    private static final byte READ_MODE = 3;
    private static UsbrfidReaderHelper mRfidHelper=null;
    private ICReaderApi mReaderApi;
    private byte BlOCK_NUMBER=4;
    private byte INITAL_ADDRESS=4;
    private String secretKey;
    private Handler  mHandler=new Handler();
    private SoundPool mSoundPool;
    private int outgoing;
    private UsbDevice mUsbDevice;
    public static UsbrfidReaderHelper getInstance(){
        if(mRfidHelper == null) {
            mRfidHelper= new UsbrfidReaderHelper();
        }
        return  mRfidHelper;
    }



    /**
     * 读取卡的秘钥
     * @param mUsbDevice
     */
    public  void   readRfid( UsbDevice  mUsbDevice){

        if (mUsbDevice!=null){
            UsbManager mUsbManager = (UsbManager) Utils.getContext().getSystemService(Context.USB_SERVICE);
            try {
                mReaderApi= new ICReaderApi(mUsbDevice, mUsbManager);
                byte[] buffer = new byte[16 * BlOCK_NUMBER];
                byte[] snr = getByteArray("31455433494F");
                int result = mReaderApi.API_PCDRead(READ_MODE,INITAL_ADDRESS,BlOCK_NUMBER,
                        snr, buffer);
                L.i("result="+result);
                if (result == 0) {
                    secretKey=convertHexToString(bytesToHexString(buffer));
                    MembershipCardEvent.postHasData(MembershipCardEvent.Message.add, secretKey);
                }else{
                    MembershipCardEvent.postNoData(MembershipCardEvent.Message.notFound);
                }

            }catch (Exception  e){
                MembershipCardEvent.postHasData(fali, Utils.getContext().getString(R.string.Read_card_failure));
            }

        }else{
            /*未连接读卡器*/
            MembershipCardEvent.postNoData(MembershipCardEvent.Message.notFound);
        }


    }



    /**
     * 读取卡号 15693
     */
    public  void  readCardNum(){
         mUsbDevice= CheckPrinterHelper.getConnectCardReader();
        if (mUsbDevice==null){
            return;
        }

        if (mSoundPool==null){
            //初始化声音池
            initSoundPool();
        }
        //清除回调和消息
        mHandler.removeCallbacksAndMessages(null);
        //发送延迟的消息
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                postReadCardNum();
                mHandler.postDelayed(this, 1500);
            }
        }, 1000);


    }

    @SuppressLint("NewApi")
    public   void  initSoundPool(){
        SoundPool.Builder builder = new SoundPool.Builder();
        //传入音频数量
        builder.setMaxStreams(2);
        //AudioAttributes是一个封装音频各种属性的方法
        AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
        //设置音频流的合适的属性
        attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        //加载一个AudioAttributes
        builder.setAudioAttributes(attrBuilder.build());
        mSoundPool= builder.build();
        outgoing=mSoundPool.load(Utils.getContext(), R.raw.success, 1);
    }

    private int playCallSounds() {
        try {
            // 播放
            int id = mSoundPool.play(outgoing, // 声音资源
                    1.0f, // 左声道
                    1.0f, // 右声道
                    1, // 优先级，0最低
                    0, // 循环次数，0是不循环，-1是永远循环
                    1); // 回放速度，0.5-2.0之间。1为正常速度
            return id;
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 读取15693 卡号
     */

    private void postReadCardNum() {
        Log.d("读取15693", "postReadCardNum: ");
        if (mUsbDevice!=null){
            UsbManager mUsbManager = (UsbManager) Utils.getContext().getSystemService(Context.USB_SERVICE);
            try {
                mReaderApi= new ICReaderApi(mUsbDevice, mUsbManager);
                byte afi = 0x00;
                byte[] pData = new byte[16];
                byte[] nrOfCard = new byte[1];
                byte[] pBuffer = new byte[32];
                byte flags = (byte)02;
                int result = mReaderApi.API_ISO15693_Inventory(flags, afi, pData,nrOfCard, pBuffer);
                L.i("postReadCardNum="+result);
                if (result == 0) {
                    String  cardNumber = showData( pBuffer,
                            1,  9 );
                    cardNumber=cardNumber.replace(" ","").trim();
                    if (cardNumber.length()>2){
                        cardNumber=cardNumber.substring(2,cardNumber.length());
                          playCallSounds();
                        MembershipCardEvent.postHasData(MembershipCardEvent.Message.cardNum, cardNumber);
                    }

                }else{


                }

            }catch (Exception  e){
                T.show(Utils.getContext().getString(R.string.Read_card_failure));
            }

        }else{
            /*未连接读卡器*/
            MembershipCardEvent.postNoData(MembershipCardEvent.Message.notFound);
        }
    }


    /**
     * 取消读卡
     */
    public   void   cancelReadCardNum(){

        mHandler.removeCallbacksAndMessages(null);
    }

    /**
     * 格式化
     * @param data
     * @param pos
     * @param len
     * @return
     */
    private String showData(  byte[] data, int pos,
                              int len) {

        StringBuffer   mStringBuffer=new StringBuffer();
        for (int i = 0; i < len; i++) {
            mStringBuffer.append(String.format("%02x ", data[i + pos]));
        }

        return mStringBuffer.toString().toUpperCase();
    }
    private byte[] getByteArray(String str) {
        str = str.replaceAll("[^0-9A-F]", "");
        byte[] ans = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i += 2) {
            ans[i / 2] = (byte) Integer.parseInt(str.substring(i, i + 2), 16);
        }
        return ans;
    }


    public  String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        int length=40;  /*秘钥是16位  保险起见20位*/
        for (int i = 0; i <length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v).toUpperCase();
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }

            stringBuilder.append(hv);



        }
        return stringBuilder.toString();
    }
    public  static String convertHexToString(String hex){
        StringBuilder sb = new StringBuilder();

        for( int i=0; i<hex.length()-1; i+=2 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));

            int decimal = Integer.parseInt(output, 16);
            if (decimal!=0){  /*0 的ascII表示NULL*/
                sb.append((char)decimal);
            }


        }

        return sb.toString();
    }
}
